﻿using System.Xml;

namespace BasecampRestAPI
{
	public class Category : ICategory
	{
		static public string PathForId(int id)
		{
			return string.Format("categories/{0}.xml", id);
		}

		#region Implementation of ICategory

		public int Id { get; private set; }
		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				string data = string.Format(Properties.Resources.UpdateCategoryRequest, value);
				_camp.Service.PutRequest(PathForId(Id), data);
				_name = value;
			}
		}
		private string _name;

		public IProject Project
		{
			get
			{
				return _camp.GetProjectById(_projectId);
			}
		}
		public int ElementsCount { get; private set; }
		public CategoryType Type { get; private set; }

		#endregion

		public static ICategory GetInstance(IBaseCamp camp, XmlNode node)
		{
			return new Category(camp, node);
		}
		private Category(IBaseCamp camp, XmlNode node)
		{
			_camp = camp;
			Id = XmlHelpers.ParseInteger(node, "id");
			_name = XmlHelpers.ChildNodeText(node, "name");
			_projectId = XmlHelpers.ParseInteger(node, "project-id");
			ElementsCount = XmlHelpers.ParseInteger(node, "elements-count");
			Type = (XmlHelpers.ChildNodeText(node, "type") == "post") ?
				CategoryType.Post : CategoryType.Attachment;
		}
		private readonly IBaseCamp _camp;
		private readonly int _projectId;
	}
}
